import React, { Component } from 'react';
import EditIdentityModal from './UserPage';
import CreateFlagModal from '../modals/CreateFlag';
import ConfirmToggleFeature from '../modals/ConfirmToggleFeature';
import TryIt from '../TryIt';
import ConfirmRemoveFeature from '../modals/ConfirmRemoveFeature';
import TagSelect from '../TagSelect';
import HistoryIcon from '../HistoryIcon';
import TagValues from '../TagValues';
import withAuditWebhooks from '../../../common/providers/withAuditWebhooks';

const FeaturesPage = class extends Component {
    static displayName = 'FeaturesPage';

    static contextTypes = {
        router: propTypes.object.isRequired,
    };

    constructor(props, context) {
        super(props, context);
        this.state = {
            tags: [],
        };
        AppActions.getFeatures(this.props.match.params.projectId, this.props.match.params.environmentId);
    }

    componentWillUpdate(newProps) {
        const { match: { params } } = newProps;
        const { match: { params: oldParams } } = this.props;
        if (params.environmentId != oldParams.environmentId || params.projectId != oldParams.projectId) {
            AppActions.getFeatures(params.projectId, params.environmentId);
        }
    }

    componentDidMount = () => {
        API.trackPage(Constants.pages.FEATURES);
        const { match: { params } } = this.props;
        AppActions.getTags(params.projectId);
        AsyncStorage.setItem('lastEnv', JSON.stringify({
            orgId: AccountStore.getOrganisation().id,
            projectId: params.projectId,
            environmentId: params.environmentId,
        }));
    };

    newFlag = () => {
        openModal('新建配置', <CreateFlagModal
          router={this.context.router}
          environmentId={this.props.match.params.environmentId}
          projectId={this.props.match.params.projectId}
        />, null, { className: 'side-modal fade' });
    };


    editFlag = (projectFlag, environmentFlag) => {
        API.trackEvent(Constants.events.VIEW_FEATURE);
        openModal('编辑配置', <CreateFlagModal
          isEdit
          router={this.context.router}
          environmentId={this.props.match.params.environmentId}
          projectId={this.props.match.params.projectId}
          projectFlag={projectFlag}
          environmentFlag={environmentFlag}
          flagId={environmentFlag.id}
        />, null, { className: 'side-modal fade' });
    };


    componentWillReceiveProps(newProps) {
        if (newProps.match.params.environmentId != this.props.match.params.environmentId) {
            AppActions.getFeatures(newProps.match.params.projectId, newProps.match.params.environmentId);
        }
    }

    onSave = () => {
        toast('环境已保存');
    };

    editIdentity = (id, envFlags) => {
        openModal(<EditIdentityModal id={id} envFlags={envFlags}/>);
    }

    confirmToggle = (projectFlag, environmentFlag, cb) => {
        openModal('Toggle Feature', <ConfirmToggleFeature
          environmentId={this.props.match.params.environmentId}
          projectFlag={projectFlag} environmentFlag={environmentFlag}
          cb={cb}
        />);
    }

    confirmRemove = (projectFlag, cb) => {
        openModal('删除配置', <ConfirmRemoveFeature
          environmentId={this.props.match.params.environmentId}
          projectFlag={projectFlag}
          cb={cb}
        />);
    }

    createFeaturePermission(el) {
        return (
            <Permission level="project" permission="CREATE_FEATURE" id={this.props.match.params.projectId}>
                {({ permission, isLoading }) => (permission ? (
                    el(permission)
                ) : this.renderWithPermission(permission, Constants.projectPermissions('Create Feature'), el(permission)))}
            </Permission>
        );
    }

    renderWithPermission(permission, name, el) {
        return permission ? (
            el
        ) : (
            <Tooltip
              title={<div>{el}</div>}
              place="right"
              html
            >{name}
            </Tooltip>
        );
    }

    onError = (error) => {
        // Kick user back out to projects
        this.setState({ error });
        if (typeof closeModal !== 'undefined') {
            closeModal();
            toast('We could not create this feature, please check the name is not in use.');
        }
    }

    filter = (flags) => {
        if (this.state.tags.length) {
            return _.filter(flags, flag => _.intersection(flag.tags || [], this.state.tags).length) || [];
        }
        return flags;
    }

    render() {
        const { projectId, environmentId } = this.props.match.params;
        return (
            <div data-test="features-page" id="features-page" className="app-container container">
                <FeatureListProvider onSave={this.onSave} onError={this.onError}>
                    {({ isLoading, projectFlags, environmentFlags }, { environmentHasFlag, toggleFlag, editFlag, removeFlag }) => (
                        <div className="features-page">
                            {isLoading && <div className="centered-container"><Loader/></div>}
                            {!isLoading && (
                                <div>
                                    {projectFlags && projectFlags.length ? (
                                        <div>
                                            <Row>
                                                <Flex>
                                                    <h3>配置列表</h3>
                                                    <p>
                                                        显示与管理
                                                        {' '}
                                                        <Tooltip
                                                          title={<ButtonLink buttonText="配置标记" />}
                                                          place="right"
                                                        >
                                                            {Constants.strings.FEATURE_FLAG_DESCRIPTION}
                                                        </Tooltip>
                                                        {' '}
                                                        和
                                                        {' '}
                                                        {' '}
                                                        <Tooltip
                                                          title={<ButtonLink buttonText="远程参数" />}
                                                          place="right"
                                                        >
                                                            {Constants.strings.REMOTE_CONFIG_DESCRIPTION}
                                                        </Tooltip>
                                                        {' '}
                                                    </p>
                                                </Flex>
                                                <FormGroup className="float-right">
                                                    {projectFlags && projectFlags.length ? this.createFeaturePermission(perm => (
                                                        <div className="text-right">
                                                            <Button
                                                              disabled={!perm} data-test="show-create-feature-btn" id="show-create-feature-btn"
                                                              onClick={this.newFlag}
                                                            >
                                                              创建配置
                                                            </Button>
                                                        </div>
                                                    ))
                                                        : null}
                                                </FormGroup>
                                            </Row>
                                            <Permission level="environment" permission="ADMIN" id={this.props.match.params.environmentId}>
                                                {({ permission, isLoading }) => (
                                                    <FormGroup className="mb-4">
                                                        <PanelSearch
                                                          className="no-pad"
                                                          id="features-list"
                                                          icon="ion-ios-rocket"
                                                          title="配置列表"
                                                          renderSearchWithNoResults
                                                          sorting={[
                                                              { label: '名称', value: 'name', order: 'asc', default: true },
                                                              { label: '创建时间', value: 'created_date', order: 'asc' },
                                                          ]}
                                                          items={this.filter(projectFlags, this.state.tags)}
                                                          header={(
                                                              <TagSelect projectId={projectId} value={this.state.tags} onChange={tags => this.setState({ tags })}/>
                                                          )}
                                                          renderRow={(projectFlag, i) => {
                                                              const { name, id, enabled, created_date, description, type } = projectFlag;
                                                              return (
                                                                  <Row
                                                                    style={{ flexWrap: 'nowrap' }}
                                                                    className={permission ? 'list-item clickable' : 'list-item'} key={id} space
                                                                    data-test={`feature-item-${i}`}
                                                                  >
                                                                      <div
                                                                        style={{ overflow: 'hidden' }}
                                                                        className="flex flex-1"
                                                                        onClick={() => permission && this.editFlag(projectFlag, environmentFlags[id])}
                                                                      >
                                                                          <div>
                                                                              <ButtonLink>
                                                                                  {name}
                                                                              </ButtonLink>
                                                                          </div>
                                                                          <div className="list-item-footer faint">
                                                                              <Row>
                                                                                  {(
                                                                                      <TagValues projectId={projectId} value={projectFlag.tags}/>
                                                                                  )}
                                                                                  <div>
                                                                                      创建于 {moment(created_date).format('YYYY-MM-DD HH:mm:ss')}{` - `}
                                                                                      {description || '没有描述'}
                                                                                  </div>
                                                                              </Row>
                                                                          </div>
                                                                      </div>
                                                                      <Row>
                                                                          {
                                                                              this.renderWithPermission(permission, Constants.environmentPermissions('Admin'), (
                                                                                  <Column>
                                                                                      {type === 'FLAG' ? (
                                                                                          <Switch
                                                                                            disabled={!permission}
                                                                                            data-test={`feature-switch-${i}${environmentFlags[id] && environmentFlags[id].enabled ? '-on' : '-off'}`}
                                                                                            checked={environmentFlags[id] && environmentFlags[id].enabled}
                                                                                            onChange={() => this.confirmToggle(projectFlag, environmentFlags[id], (environments) => {
                                                                                                toggleFlag(_.findIndex(projectFlags, { id }), environments);
                                                                                            })}
                                                                                          />
                                                                                      ) : (
                                                                                          <FeatureValue
                                                                                            onClick={() => permission && this.editFlag(projectFlag, environmentFlags[id])}
                                                                                            value={environmentFlags[id] && environmentFlags[id].feature_state_value}
                                                                                            data-test={`feature-value-${i}`}
                                                                                          />
                                                                                      )}
                                                                                  </Column>
                                                                              ))
                                                                            }

                                                                          {AccountStore.getOrganisationRole() === 'ADMIN' && (
                                                                          <Tooltip
                                                                            html
                                                                            title={(
                                                                                <button
                                                                                  onClick={() => {
                                                                                      this.context.router.history.push(`/project/${projectId}/environment/${environmentId}/audit-log?env=${environmentId}&search=${projectFlag.name}`);
                                                                                  }}
                                                                                  className="btn btn--with-icon"
                                                                                  data-test={`feature-history-${i}`}
                                                                                >
                                                                                    <HistoryIcon/>
                                                                                </button>
                                                                              )}
                                                                          >
                                                                            配置历史
                                                                          </Tooltip>
                                                                          )}
                                                                          <Permission level="project" permission="DELETE_FEATURE" id={this.props.match.params.projectId}>
                                                                              {({ permission: removeFeaturePermission }) => this.renderWithPermission(removeFeaturePermission, Constants.projectPermissions('Delete Feature'), (
                                                                                  <Column>
                                                                                      <Tooltip
                                                                                        html
                                                                                        title={(
                                                                                            <button
                                                                                              disabled={!removeFeaturePermission}
                                                                                              onClick={() => this.confirmRemove(projectFlag, () => {
                                                                                                  removeFlag(this.props.match.params.projectId, projectFlag);
                                                                                              })}
                                                                                              className="btn btn--with-icon"
                                                                                              data-test={`remove-feature-btn-${i}`}
                                                                                            >
                                                                                                <RemoveIcon/>
                                                                                            </button>
                                                                                        )}
                                                                                      >
                                                                                      删除配置
                                                                                      </Tooltip>
                                                                                  </Column>
                                                                              ))}
                                                                          </Permission>
                                                                      </Row>
                                                                  </Row>
                                                              );
                                                          }}
                                                          filterRow={({ name }, search) => name.toLowerCase().indexOf(search) > -1}
                                                        />
                                                    </FormGroup>
                                                )}

                                            </Permission>
                                            <FormGroup>
                                                <CodeHelp
                                                  title="1: 安装SDK"
                                                  snippets={Constants.codeHelp.INSTALL}
                                                />
                                                <CodeHelp
                                                  title="2: 初始化"
                                                  snippets={Constants.codeHelp.INIT(this.props.match.params.environmentId, projectFlags && projectFlags[0] && projectFlags[0].name)}
                                                />
                                            </FormGroup>
                                            <FormGroup>
                                                <TryIt
                                                  title="测试此环境中从API返回的值"
                                                  environmentId={this.props.match.params.environmentId}
                                                />
                                            </FormGroup>
                                        </div>
                                    ) : (
                                        <div>
                                            <h3>创建新的配置</h3>

                                            <FormGroup>
                                                <Panel icon="ion-ios-rocket" title="1. 创建配置">
                                                    <p>
                                                        可以为项目创建两种配置类型:
                                                        <ul>
                                                            <li>
                                                                <strong>标记类型</strong>
                                                                : 允许使用按钮切换开启关闭:
                                                                <p className="faint">
                                                                    例如: 开启一个新的功能仅在测试环境生效
                                                                </p>
                                                            </li>
                                                            <li>
                                                                <strong>远程配置</strong>
                                                                : 根据特性进行配置
                                                                <p className="faint">
                                                                    例如: 可以进行任意搜索配置
                                                                </p>
                                                            </li>
                                                        </ul>
                                                    </p>
                                                </Panel>
                                            </FormGroup>
                                            <FormGroup>
                                                <Panel
                                                  icon="ion-ios-settings"
                                                  title="2. 为每个环境创建配置"
                                                >
                                                    <p>
                                                        系统将自动为项目创建
                                                        {' '}
                                                        <strong>Development</strong>
                                                        {' '}
                                                        和
                                                        {' '}
                                                        <strong>Production</strong>
                                                        .
                                                        默认情况创建一个配置将同步到所有环境, 当然您可以单独进行配置.
                                                    </p>
                                                </Panel>
                                            </FormGroup>

                                            <FormGroup>
                                                <Panel
                                                  icon="ion-ios-person"
                                                  title="3. 配置用户标识"
                                                >
                                                    <p>
                                                        当使用sdk时, 会自动创建用户标识
                                                        {' '}
                                                        <strong>identify</strong>
                                                        {' '}
                                                        
                                                        {' '}
                                                        <Link
                                                          className="btn--link"
                                                          to={`/project/${projectId}/environment/${environmentId}/users`}
                                                        >
                                                            用户页面
                                                        </Link>.
                                                    </p>
                                                </Panel>
                                            </FormGroup>
                                            {this.createFeaturePermission(perm => (
                                                <FormGroup className="text-center">
                                                    <Button
                                                      disabled={!perm}
                                                      className="btn-lg btn-primary" id="show-create-feature-btn" data-test="show-create-feature-btn"
                                                      onClick={this.newFlag}
                                                    >
                                                        <span className="icon ion-ios-rocket"/>
                                                        {' '}
                                                      创建配置
                                                    </Button>
                                                </FormGroup>
                                            ))}
                                        </div>
                                    )}

                                </div>
                            )}
                        </div>
                    )}
                </FeatureListProvider>
            </div>
        );
    }
};

FeaturesPage.propTypes = {};

module.exports = hot(module)(ConfigProvider(FeaturesPage));
